<!--车辆终身质保审核 厂端-->
<template>
  <div>
    <TopFilter :list="topFilterList" :cols="4" labelWidth="100" :collapse="true" @filterChange="changeHandle" ref="topfilter" @resetChange="resetChange" @onCollapse="collapseHandle"></TopFilter>
    <FilterTable
      :onSyncTableData="tableChange"
      :onRowSelectChange="selectChange"
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      datakey="records"
      :isSelectColumn="true"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <template slot="controls" slot-scope="props">
        <!--<multiuse-button type="primary" class="btnStyle" :click="batchReview.bind(this,1)">批量审核</multiuse-button>-->
        <!-- <multiuse-button type="primary" class="btnStyle" :click="batchReview.bind(this, 2)">批量驳回</multiuse-button> -->
        <ajax-button type="primary" class="btnStyle" :click="addRule">新增</ajax-button>
        <ajax-button type="primary" class="btnStyle" :click="deleteRule">删除</ajax-button>
        <ajax-button size="small" type="primary" icon="el-icon-download" :click="downHandle.bind(this, 0)">删除模板下载</ajax-button>
        <ajax-button size="small" type="primary" icon="el-icon-download" :click="downHandle.bind(this, 1)">新增模板下载</ajax-button>
        <UploadFile style="margin: 0 10px;" isOnlyButton :limit="20" type="primary" :fileTypes="['xls', 'xlsx']" icon="el-icon-upload" :actionUrl="addActionUrl" @change="successHandler"
          >导入新增
        </UploadFile>
        <UploadFile style="margin: 0 10px;" isOnlyButton :limit="20" type="primary" :fileTypes="['xls', 'xlsx']" icon="el-icon-upload" :actionUrl="deleteActionUrl" @change="successHandler"
          >导入删除
        </UploadFile>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visibleDetail" :title="dialogTitle" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <detail :specialWarrantyId="specialWarrantyId" @close="closeHandler" :handleType="handleType" />
    </BaseDialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { dictionary } from '@/utils/dictMixin';
import moment from 'moment';
import detail from './detail';

import { isEmpty } from '@/utils/utils';
import { dealerMixin } from '@/pages/repair/batchEventManagement/dealerMixin';
import { downSpecialAdd, downSpecialDelete, vehicleSpecialWarrantyList, deleteVehicleSpecialWarranty } from '@/api/repair/newEnergyVehicleLifetime/vehicleLifetimeReviewCDuan';
import { findTableItem, exportExcelFile } from '@/utils';
import { getAllDealer } from '@/api/repair/repairManage/repairQuery/index.js';
import { getAppId } from '@/assets/js/auth';

export default {
  name: 'addItem',
  mixins: [dictionary, dealerMixin],
  data() {
    this.BaseTable = null;
    this.conf = { add: '新增', edit: '编辑', show: '审核' };
    return {
      topFilterList: this.createTopFilterList(),
      visibleDelear: false,
      visibleDetail: false,
      visibleCarModel: false,
      visibleReason: false,
      fetchApi: vehicleSpecialWarrantyList,
      dialogTitle: '',
      reasonTitle: '',
      fetchParams: { xhrAbort: true },
      columns: this.createTableColumnsArcfox(),
      handleType: '',
      formData: {},
      specialWarrantyId: '',
      selectArr: [],
      /*表格在中数据*/
      tableData: [],
      batchType: 1,
      selectDealer: null,
      selectCar: null,
      addActionUrl: '/api/dmscloud.activity/ttRpVehicleWarranty/importVehicleSpecialWarrantyAdd',
      deleteActionUrl: '/api/dmscloud.activity/ttRpVehicleWarranty/importVehicleSpecialWarrantyDelete'
    };
  },
  components: {
    detail
  },

  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    if (getAppId() == 'arcfox') {
      this.columns = this.createTableColumnsArcfox();
      //翻译经销商
      // this.getAllDealer();
    } else {
      this.columns = this.createTableColumns();
    }
    // this.getAllUsers(this.columns, ['updatedBy'], 'table');
  },
  methods: {
    /*下载模板*/
    downHandle(type) {
      this.handleType = 'down';
      this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (type == 1) {
            downSpecialAdd()
              .then(res => {
                console.log(res, 'res');
                exportExcelFile(res.data, '特殊质保新增模板');
              })
              .catch(err => {});
          } else {
            downSpecialDelete()
              .then(res => {
                console.log(res, 'res');
                exportExcelFile(res.data, '特殊质保删除模板');
              })
              .catch(err => {});
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    // 获取所有的经销商
    async getAllDealer() {
      let res = await getAllDealer();
      if (res.resultCode == 200) {
        let allDealer = res.data.map(x => ({ text: x.dealerShortname, value: x.dealerCode + '' }));
        this.columns.find(x => x.dataIndex == 'ownerCode').dictItems = allDealer;
        // this.columns.find(x => x.dataIndex === 'ownerCode').dictItems = allDealer;
      }
    },
    dealerTranslate() {
      let userIds = [];
      this.tableData.forEach(item => {
        userIds.push(item.updatedBy);
      });
      if (!userIds.length) return;
      let newUserIds = Array.from(new Set(userIds)); // 数组去重
      this.getNameByIds(this.columns, newUserIds.join(','), ['updatedBy'], 'table');
    },
    tableChange(data) {
      this.tableData = data;
      // this.dealerTranslate();
      let disabledSelect = this.tableData.filter(row => row.status == '10221002');
      this.BaseTable.SET_DISABLE_SELECT(disabledSelect);
    },

    /*配置数量发生改变的时候执行*/
    selectChange(val) {
      this.selectArr = val;
    },

    /*选择经销啥昂*/
    selectDelearFun(arr) {
      let row = arr[0];
      this.selectDealer = row;
      this.topFilterList.find(item => item.fieldName == 'resDealer').initialValue = row['dealerName'];
    },
    /*选择车型*/
    selectCarFun(arr) {
      let row = arr[0];
      console.log('row', row);
      this.selectCar = row;
      this.topFilterList.find(item => item.fieldName == 'model').initialValue = row['modelName'];
    },
    dealerFun() {
      this.visibleDelear = true;
    },

    carModelFun() {
      this.visibleCarModel = true;
    },
    // 导出处理函数
    handleExportFun(row) {
      row.status = this.createDictText(row.status, 1022);
    },
    async deleteRule() {
      if (this.selectArr.length == 0) {
        this.$notify.warning({ title: '提示信息', message: '请您先选择数据' });
        return;
      }
      let ids = this.selectArr.map(item => item.specialWarrantyId);
      let res = await deleteVehicleSpecialWarranty(ids);
      if (res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '删除成功!' });
        this.fetchParams = Object.assign({ xhrAbort: false }, this.fetchParams);
      }
    },
    detailHandle(row) {
      this.specialWarrantyId = row['specialWarrantyId'];
      this.handleType = 'edit';
      this.showHandler();
    },
    addRule() {
      this.specialWarrantyId = '';
      this.handleType = 'add';
      this.showHandler();
    },
    createTableColumnsArcfox() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          sorter: true,
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          render: props => {
            return (
              <div>
                <multiuse-button
                  type="text"
                  size="mini"
                  // disabled={rst}
                  click={() => this.detailHandle(props.row)}
                >
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          filter: true
        },
        {
          title: '质保里程(单位km)',
          dataIndex: 'warrantyMileage',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '质保时间(单位年)',
          dataIndex: 'warrantyTime',
          width: 150,
          sorter: true
        },
        {
          title: '质保类型',
          dataIndex: 'warrantyType',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          sorter: true,
          width: 70,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          render: props => {
            return (
              <div>
                <multiuse-button
                  type="text"
                  size="mini"
                  // disabled={rst}
                  click={() => this.detailHandle(props.row)}
                >
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '质保类型',
          dataIndex: 'warrantyType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          dictItems: this.createDictList(8888),
          filterItems: this.createDictList(8888)
        },
        {
          title: '是否首任车主',
          dataIndex: 'isFirstOwner',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          dictItems: this.createDictList(1004),
          filterItems: this.createDictList(1004)
        },

        {
          title: '质保里程(单位km)',
          dataIndex: 'warrantyMileage',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '质保时间(单位年)',
          dataIndex: 'warrantyTime',
          width: 150,
          sorter: true,
          dateFormat: 'yyyy-MM-dd'
        }
      ];
    },
    createTopFilterList() {
      return [
        {
          type: 'TEXT_AREA',
          label: 'vin',
          fieldName: 'vin'
        },
        {
          type: 'RANGE_DATE',
          label: '更新日期',
          dateType: 'daterange',
          fieldName: 'bUpdatedAt|eUpdatedAt'
        }
      ];
    },
    successHandler(e) {
      console.log('e:::', e);
      if (e != 1) {
        let obj = e[e.length - 1];
        let data = obj['url'];
        // let success = data['success'];
        let successArr = data['success'];
        let failArr = data['fail'];
        if (!failArr) {
          failArr = '';
        } else {
          failArr = ',' + failArr;
        }
        this.$notify.success({ title: '提示信息', message: successArr + failArr });
        this.fetchParams = Object.assign({ xhrAbort: false }, this.fetchParams);
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    resetChange(val) {
      this.selectCar = null;
      this.selectDealer = null;
      console.log(val, 'val');

      // this.$refs.topfilter.RESET_FORM();
      let obj = Object.assign({}, val);
      this.fetchParams = obj;
    },
    changeHandle(val) {
      let obj = Object.assign({}, val);
      let resDealer = isEmpty(this.selectDealer) ? '' : this.selectDealer.dealerCode;
      let model = isEmpty(this.selectCar) ? '' : this.selectCar.modelCode;
      obj['resDealer'] = resDealer;
      obj['model'] = model;
      this.fetchParams = obj;
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}车辆终身质保规则定义`;

      this.visibleDetail = true;
    },
    closeHandler(type = '') {
      this.visibleReason = false;
      this.visibleDelear = false;
      this.visibleDetail = false;
      this.visibleCarModel = false;
      this.fetchParams = { ...this.fetchParams };
    }
  }
};
</script>

<style lang="less" scoped></style>
